import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/utils/file_util.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/data/api/file_upload_apis.dart';

///自定义视频选择器
/// [title] 标题
/// [callback] 回调
/// [videoList] 已选择的视频列表
/// [isRequired] 是否必填
/// [maxCount] 最大选择数量
/// [titleTextStyle] 标题文字样式
///[isEnabled] 是否可编辑
///[isChange] 是否在交接班中
/// demo:
/// ``` dart
/// CustomPickerVideo(
///   title: '标题',
///   imagesList: [],
///   titleTextStyle: TextStyle(),
///   isEnabled: false,
///   isRequired: false,
///   onCallBack: (List<String> value){},
/// );
/// ```
class CustomPickerVideo extends StatefulWidget {
  const CustomPickerVideo({
    required this.title,
    required this.videoList,
    this.callback,
    super.key,
    this.isRequired = false,
    this.maxCount,
    this.titleTextStyle,
    this.isEnabled = true,
    this.isChange = false,
  });

  final String title; //标题
  final List<String> videoList; // 已选择的视频列表
  final bool isRequired; //是否必填
  final int? maxCount; //最大选择数量
  final Function(List<String> path)? callback; //回调
  final TextStyle? titleTextStyle; // 标题文字样式
  final bool isEnabled; //是否可编辑
  final bool isChange; //是否在交接班中

  @override
  State<CustomPickerVideo> createState() => _CustomPickerVideoState();
}

class _CustomPickerVideoState extends State<CustomPickerVideo> {
  // //当前显示的内容
  // List<String> videoList = [];

  @override
  void initState() {
    super.initState();
    _initView();
  }

  _initView() {
    // if (widget.videoList != null && widget.videoList!.isNotEmpty && widget.videoList![0].isNotEmpty) {
    //   videoList.addAll(widget.videoList!);
    // }
  }

  /// 拍摄或者从相册中选择视频
  void selectVideo(ImageSource source) async {
    final ImagePicker picker = ImagePicker();

    /// 从相册中选取
    final XFile? image = await picker.pickVideo(source: source, maxDuration: const Duration(minutes: 10));
    if (image != null) {
      final images = await FileUploadApis.uploadFile(fileUrl: image.path);
      if (images != '') {
        widget.videoList.add(images);
        //进行回调
        if (widget.callback != null) {
          widget.callback!(widget.videoList);
        }
        setState(() {});
      } else {
        AppToast.showWarning('上传失败');
      }
    }
    // else {
    //   AppToast.showWarning('未选择视频');
    // }
  }

  /// 判断是否还能添加视频
  Widget addVideo(List<String> images) {
    if (!widget.isEnabled) {
      return Container();
    }
    if (images.length < (widget.maxCount ?? 9)) {
      return Container(
        width: 80.w,
        height: 80.w,
        margin: EdgeInsets.only(bottom: 10.w),
        decoration: BoxDecoration(
          color: const Color(0xffF7F7FB),
          border: Border.all(
            color: const Color(0xffEBEDF0),
          ),
          borderRadius: BorderRadius.circular(8.w),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.photo_camera_outlined,
              color: const Color(0xff8D95A3),
              size: 25.w,
            ),
            AppGaps.vGap6,
            Text(
              '点击上传',
              style: TextStyle(
                color: const Color(0xffC6CFE0),
                height: 1.2,
                fontSize: 14.sp,
              ),
            ),
          ],
        ),
      ).clickOnce(() {
        showCupertinoModalPopup(
          context: context,
          builder: (context) {
            return CupertinoActionSheet(
              actions: [
                CupertinoActionSheetAction(
                  child: const Text('拍摄'),
                  onPressed: () {
                    Navigator.of(context).pop();
                    selectVideo(ImageSource.camera);
                  },
                ),
                CupertinoActionSheetAction(
                  child: const Text('从相册选择'),
                  onPressed: () {
                    Navigator.of(context).pop();
                    selectVideo(ImageSource.gallery);
                  },
                ),
              ],
              cancelButton: CupertinoActionSheetAction(
                onPressed: Navigator.of(context).pop,
                child: const Text('取消'),
              ),
            );
          },
        );
      });
    } else {
      return Container();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        AppGaps.vGap10,
        Row(
          children: [
            Visibility(visible: widget.isRequired, child: Text('*', style: TextStyle(color: Colors.red, fontSize: 14.sp))),
            AppGaps.hGap2,
            Text(
              widget.title,
              style: widget.titleTextStyle ??
                  TextStyle(
                    fontSize: 14.sp,
                    height: 1.1,
                    color: AppColors.font_color_black,
                  ),
            ),
            const Spacer(),
            Text(
              '${widget.videoList.length}/${widget.maxCount ?? 9}',
              style: TextStyle(color: const Color(0xff8D95A3), fontSize: 12.sp),
            ),
          ],
        ),
        AppGaps.vGap12,
        Wrap(
          spacing: 5.w,
          children: widget.videoList.map<Widget>((item) {
            return Stack(
              children: [
                Container(
                  width: 80.w,
                  height: 80.w,
                  margin: const EdgeInsets.only(bottom: 10),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: const Color(0xff333333),
                    border: Border.all(
                      color: const Color(0xffEBEDF0),
                    ),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: IconButton(
                    icon: const Icon(
                      Icons.play_circle,
                      color: Colors.white,
                      size: 30,
                    ),
                    onPressed: () {
                      FileUtils.openFile(item.contains('http') ? item : Interface.fileUrl + item);
                    },
                  ),
                ),
                Visibility(
                    visible: widget.isEnabled && !widget.isChange,
                    child: Positioned(
                      right: 5.w,
                      top: 5.w,
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            widget.videoList.remove(item);
                            //进行回调
                            if (widget.callback != null) {
                              widget.callback!(widget.videoList);
                            }
                          });
                        },
                        child: Container(
                          width: 20.w,
                          height: 20.w,
                          decoration: BoxDecoration(
                            color: const Color(0xffF7F7FB),
                            borderRadius: BorderRadius.circular(10.w),
                          ),
                          child: Icon(
                            Icons.close,
                            color: const Color(0xff8D95A3),
                            size: 15.w,
                          ),
                        ),
                      ),
                    )),
              ],
            );
          }).toList()
            ..add(addVideo(widget.videoList)),
        ),
        AppGaps.vGap5,
      ],
    );
  }
}
